﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Newtonsoft.Json;
using UnityEditor.Build.Reporting;

using UnityEditor.Callbacks;
#if UNITY_IOS 
//using ChillyRoom.UnityEditor.iOS.Xcode;
using UnityEditor.iOS.Xcode;
#endif

class AndroidKeyStoreInfo
{
    public string keystorePass;
    public string keyaliasName;
    public string keyaliasPass;
}



public class BuildTool
{
    public static void SetBuildSetting()
    {
		bool il2cpp = true;
        bool development = false;
        bool nativeDebug = false;
		string[] args = System.Environment.GetCommandLineArgs();
		for (int i = 0; i < args.Length; i++)
		{
			string arg = args[i];
			if (arg == "-il2cpp")
			{
                il2cpp = bool.Parse(args[++i]);
				break;
			}

            if (arg == "-development")
            {
                development = bool.Parse(args[++i]);
                break;
            }

            if (arg == "-native_debug")
            {
                nativeDebug = bool.Parse(args[++i]);
                break;
            }
		}
            
        EditorUserBuildSettings.iOSBuildConfigType = nativeDebug? iOSBuildType.Debug: iOSBuildType.Release;
        EditorUserBuildSettings.androidBuildType = nativeDebug? AndroidBuildType.Debug: AndroidBuildType.Release;

        EditorUserBuildSettings.development = development;

		if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
		{
            PlayerSettings.SetScriptingBackend (BuildTargetGroup.Android, il2cpp? ScriptingImplementation.IL2CPP: ScriptingImplementation.Mono2x);
		}
		else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
		{
			PlayerSettings.SetScriptingBackend (BuildTargetGroup.iOS, ScriptingImplementation.IL2CPP);
		}

        AssetDatabase.SaveAssets ();
    }


    public static void SetDevelopmentBuildByCmd()
    {
        if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
        {
            //            EditorUserBuildSettings.iOSBuildConfigType = iOSBuildType.Debug;
        }
        else
        {
            //            EditorUserBuildSettings.androidBuildType = AndroidBuildType.Debug;
        }

        bool developmentBuild = true;
        string[] args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            string arg = args[i];
            if (arg == "-development_build")
            {
                developmentBuild = bool.Parse(args[++i]);
            }
        }

        EditorUserBuildSettings.development = developmentBuild;
        AssetDatabase.SaveAssets();
    }

    [MenuItem("Custom/Build/SetAndoridKeyStore")]
    public static void SetAndoridKeyStore()
    {
        string compileType = VersionEx.compile_type.ToString();
        string keyStorePath = "project_build_setting/android_key_file/" + compileType + ".keystore";
        string keyStoreConfigPath = "project_build_setting/android_key_file/" + compileType + "-config.txt";
        if(!System.IO.File.Exists(keyStorePath))
        {
            keyStorePath = "Assets/zframework/android_key_file/" + compileType + ".keystore";
            keyStoreConfigPath = "Assets/zframework/android_key_file/" + compileType + "-config.txt";
        }

        if(!System.IO.File.Exists(keyStoreConfigPath))
        {
            throw new System.Exception("file not exists:" + keyStoreConfigPath);
        }

        AndroidKeyStoreInfo keyStoreInfo = JsonConvert.DeserializeObject<AndroidKeyStoreInfo>(CommonUtil.fileToString(keyStoreConfigPath));

        PlayerSettings.Android.keystoreName = keyStorePath;
        PlayerSettings.Android.keystorePass = keyStoreInfo.keystorePass;
        PlayerSettings.Android.keyaliasName = keyStoreInfo.keyaliasName;
        PlayerSettings.Android.keyaliasPass = keyStoreInfo.keyaliasPass;
    }

    public static void BuildByCmd()
    {
        string outputPath = null;
        bool developmentBuild = true;
        string[] args = System.Environment.GetCommandLineArgs();
        for (int i = 0; i < args.Length; i++)
        {
            string arg = args[i];
            if (arg == "-output_path")
            {
                outputPath = args[++i];
            }
            else if (arg == "-development_build")
            {
                developmentBuild = bool.Parse(args[++i]);
            }
        }

        EditorUserBuildSettings.development = developmentBuild;

        switch (EditorUserBuildSettings.activeBuildTarget)
        {
            case BuildTarget.Android:
                {
                    BuildAndroidProject(outputPath);
                }
                break;
            case BuildTarget.iOS:
                {
                    BuildIOS_Project(outputPath);
                }
                break;
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:
            case BuildTarget.StandaloneOSX:
            case BuildTarget.StandaloneOSXIntel:
            case BuildTarget.StandaloneOSXIntel64:
                {
                    BuildStandalone(outputPath);
                }
                break;
        }
    }

	[MenuItem("Custom/Build/Build")]
    public static void Build()
    {
        switch (EditorUserBuildSettings.activeBuildTarget)
        {
            case BuildTarget.Android:
                {
                    BuildAndroidProject();
                }
                break;
            case BuildTarget.iOS:
                {
                    BuildIOS_Project();
                }
                break;
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:
            case BuildTarget.StandaloneOSX:
            case BuildTarget.StandaloneOSXIntel:
            case BuildTarget.StandaloneOSXIntel64:
                {
                    BuildStandalone();
                }
                break;
        }
    }

	[MenuItem("Custom/Build/BuildStandalone")]
    public static void BuildStandalone()
    {
        Build2(BuildTargetGroup.Standalone, "standalone_build", BuildOptions.None);
    }

    public static void BuildStandalone(string outputPath)
    {
        Build2(BuildTargetGroup.Standalone, outputPath, BuildOptions.None);
    }


    public static void BuildAndroidProject(string outputPath)
    {
        Build2(BuildTargetGroup.Android, outputPath, BuildOptions.AcceptExternalModificationsToPlayer);
    }

	[MenuItem("Custom/Build/BuildAndroidProject")]
    public static void BuildAndroidProject()
    {
        Build2(BuildTargetGroup.Android, "android_build", BuildOptions.AcceptExternalModificationsToPlayer);
    }

//    [MenuItem("Custom/Build/BuildAndroidApk")]
//    public static void BuildAndroidApk()
//    {
//        Build2(BuildTargetGroup.Android, "android_build/" + PlayerSettings.productName + ".apk", BuildOptions.None);
//    }

	[MenuItem("Custom/Build/BuildIOS_Project")]
    public static void BuildIOS_Project()
    {
        Build2(BuildTargetGroup.iOS, "ios_build", BuildOptions.None);
    }

    public static void BuildIOS_Project(string outputPath)
    {
        Build2(BuildTargetGroup.iOS, outputPath, BuildOptions.None);
    }

    public static BuildTarget GetTarget(BuildTargetGroup targetGroup)
    {
        BuildTarget target = BuildTarget.NoTarget;
        if (targetGroup == BuildTargetGroup.Android)
        {
            target = BuildTarget.Android;
            EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
        }
        else if (targetGroup == BuildTargetGroup.iOS)
        {
            target = BuildTarget.iOS;
        }
        else if (targetGroup == BuildTargetGroup.Standalone)
        {
            if (Application.platform == RuntimePlatform.OSXEditor)
            {
                target = BuildTarget.StandaloneOSX;
            }
            else if (Application.platform == RuntimePlatform.WindowsEditor)
            {
                target = BuildTarget.StandaloneWindows64;
            }
        }

        return target;
    }

    [MenuItem("Custom/Build/PresetBuild")]
    public static void PresetBuild()
    {
        BuildTargetGroup group = EditorUserBuildSettings.selectedBuildTargetGroup;
        if (group == BuildTargetGroup.Standalone)
        {
            if (!EditorUserBuildSettings.activeBuildTarget.ToString().ToLower().Contains("standalone"))
            {
                group = (BuildTargetGroup)System.Enum.Parse(typeof(BuildTargetGroup), EditorUserBuildSettings.activeBuildTarget.ToString());
            }
        }
        PresetBuild(group);
    }

    public static void PresetBuild(BuildTargetGroup targetGroup)
    {
        AssetDatabase.Refresh();

        if (EditorSwitchConfig.encodeLua)
        {
            System.IO.Directory.CreateDirectory(ResourcesEx.BundleResDir + "/LuaTemp");
            Packager.BuildAssetResource (ResourcesEx.BundleResDir, targetGroup, true, Packager.Cpu._64);
            System.IO.Directory.Move(ResourcesEx.BundleResDir + "/Lua", ResourcesEx.BundleResDir + "/LuaTemp/64");
            Packager.BuildAssetResource (ResourcesEx.BundleResDir, targetGroup, true, Packager.Cpu._32);
            System.IO.Directory.Move(ResourcesEx.BundleResDir + "/Lua", ResourcesEx.BundleResDir + "/LuaTemp/32");        
            System.IO.Directory.Move(ResourcesEx.BundleResDir + "/LuaTemp", ResourcesEx.BundleResDir + "/Lua");
        }
        else
        {
            System.IO.Directory.CreateDirectory(ResourcesEx.BundleResDir + "/LuaTemp");
            ToLuaMenu.CopyLuaFilesToRes(ResourcesEx.BundleResDir);
            System.IO.Directory.Move(ResourcesEx.BundleResDir + "/Lua", ResourcesEx.BundleResDir + "/LuaTemp/64");
            ToLuaMenu.CopyLuaFilesToRes(ResourcesEx.BundleResDir);
            System.IO.Directory.Move(ResourcesEx.BundleResDir + "/Lua", ResourcesEx.BundleResDir + "/LuaTemp/32");        
            System.IO.Directory.Move(ResourcesEx.BundleResDir + "/LuaTemp", ResourcesEx.BundleResDir + "/Lua");
        }

        ShaderTool.BuildShaderVariantCollection();
    }

    public static void Build2(BuildTargetGroup targetGroup, string dir, BuildOptions opt)
    {
        BuildTarget target = GetTarget(targetGroup);

        if (EditorUserBuildSettings.selectedBuildTargetGroup != targetGroup)
        {
            EditorUserBuildSettings.SwitchActiveBuildTarget(targetGroup, target);
            EditorUserBuildSettings.selectedBuildTargetGroup = targetGroup;
        }

		if (dir.Contains ("."))
		{
			string realDir = System.IO.Path.GetDirectoryName (dir);
			if (System.IO.Directory.Exists(realDir))
			{
				System.IO.Directory.Delete(realDir, true);
			}
		}

        if (System.IO.Directory.Exists(dir))
        {
            System.IO.Directory.Delete(dir, true);
        }

        if(target == BuildTarget.StandaloneWindows64)
        {
            System.IO.Directory.CreateDirectory(dir);
            dir += "/" + PlayerSettings.productName + ".exe";
        }

        string[] LevelArray = GetScenePaths();
        //opt |= BuildOptions.AutoRunPlayer | BuildOptions.ShowBuiltPlayer;
//        if (VersionEx.compile_type != CompileType.release && target != BuildTarget.Android)

        if (EditorUserBuildSettings.development)
        {
            opt |= BuildOptions.Development;
        }

        Debug.Log("build with options: " + opt);

        if (targetGroup == BuildTargetGroup.Android)
        {
            // PlayerSettings.Android.targetSdkVersion = AndroidSdkVersions.AndroidApiLevel26;
            VersionTool.SetSdkConfig();

            SetAndoridKeyStore();
			string destDir = "Assets/Plugins/Android";
            string[] paths = System.IO.Directory.GetDirectories("Assets", "Plugins", System.IO.SearchOption.AllDirectories);
            for (int i = 0; i < paths.Length; i++)
            {
                string path = paths[i];
                if (path.Contains("Assets/Plugins"))
                {
                    continue;
                }

                string androidDir = path + "/Android";
                
                if (System.IO.Directory.Exists(androidDir))
                {
                    //for EasyMovieTexture
                    string[] needCopyDirs = System.IO.Directory.GetDirectories(androidDir, "*", System.IO.SearchOption.TopDirectoryOnly);
                    for (int j = 0; j < needCopyDirs.Length; j++)
                    {
                        string needCopyDir = needCopyDirs[j];
                        string dirName = System.IO.Path.GetFileName(needCopyDir);
                        if (dirName == "libs")
                        {
                            continue;
                        }

                        string[] files = System.IO.Directory.GetFiles(needCopyDir, "*", System.IO.SearchOption.AllDirectories);
                        for (int k = 0; k < files.Length; k++)
                        {
                            string file = files[k];
                            string destFile = file.Replace(androidDir, destDir);
                            string destDirPath = System.IO.Path.GetDirectoryName(destFile);
                            CommonUtil.CreateDir(destDirPath);
                            CommonUtil.Move(file, destFile);
                        }
                            
                        string metaFilePath = needCopyDir + ".meta";
                        if (!System.IO.File.Exists(metaFilePath))
                        {
                            CommonUtil.Move(metaFilePath, destDir + "/" + dirName + ".meta");
                        }
                    }
                }
            }

			string[] libsPaths = System.IO.Directory.GetDirectories (destDir, "libs", System.IO.SearchOption.AllDirectories);
			for(int i = 0; i < libsPaths.Length; i++)
			{
				string libsPath = libsPaths [i];
                if (System.IO.Path.GetFileName(System.IO.Path.GetDirectoryName (libsPath)) != "Android")
				{
					string[] filePaths = System.IO.Directory.GetFiles (libsPath, "*", System.IO.SearchOption.AllDirectories);
					for (int j = 0; j < filePaths.Length; j++)
					{
						string filePath = filePaths[j];
						string destFilePath = filePath.Replace (libsPath, destDir + "/libs");
						CommonUtil.CreateDir (System.IO.Path.GetDirectoryName (destFilePath));
                        CommonUtil.Move(filePath, destFilePath);
					}
				}
			}

            AssetDatabase.Refresh();
        }

//        BuildLogHandler logHandler = new BuildLogHandler();
        BuildReport errorMsg = null;
//        try
//        {
            Debug.Log("BuildPipeline.BuildPlayer begin:  target:" + target + "   dir:" + dir);
            errorMsg = BuildPipeline.BuildPlayer(LevelArray, dir, target, opt);
            Debug.Log("BuildPipeline.BuildPlayer end");
//        }
//        catch(System.Exception e)
//        {
//        }
//        finally
//        {
//            logHandler.Destroy();
//        }

        if (errorMsg != null && errorMsg.summary.result == BuildResult.Succeeded)
        {
            if(targetGroup == BuildTargetGroup.Android)
            {
                string parentDir = System.IO.Path.GetDirectoryName(dir);
                string srcDir = dir + "/" + PlayerSettings.productName;
                string tempDir = PlayerSettings.productName;
                if (!string.IsNullOrEmpty(parentDir))
                {
                    tempDir = parentDir + "/" + PlayerSettings.productName;
                }
                Debug.Log("srcDir: " + srcDir + "  tempDir: " + tempDir + "  dir: " + dir);

                CommonUtil.Move(srcDir, tempDir);
                CommonUtil.Move(tempDir, dir);
            }


            bool customConfigEnable = true;
            if(!customConfigEnable)
            {
                return;
            }

            if (targetGroup == BuildTargetGroup.Android)
            {
                string manifestFilePath = dir + "/src/main/AndroidManifest.xml";
                System.IO.File.Copy(manifestFilePath, manifestFilePath + ".backup");


                bool enableBugly = false;
                if(enableBugly)
                {
                    //for bugly
                    HashSet<string> addPermissions = new HashSet<string>(){ "android.permission.INTERNET", "android.permission.ACCESS_NETWORK_STATE", "android.permission.ACCESS_WIFI_STATE", "android.permission.READ_PHONE_STATE", "android.permission.READ_LOGS" };
                    AddPermissionToManifest(manifestFilePath, addPermissions);
                }



                AddAfter(manifestFilePath, @"<application ", @" android:usesCleartextTraffic=""true"" ");

                bool enableReadIMEI = true;
                if (enableReadIMEI)
                {
                    HashSet<string> addPermissions = new HashSet<string>(){"android.permission.READ_PHONE_STATE"};
                    AddPermissionToManifest(manifestFilePath, addPermissions);
                }


                bool enableMipush = false;
                if(enableMipush)
                {
                    string packageName = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android);

                    // //for mipush begin
                    // HashSet<string> addPermissions = new HashSet<string>(){ "android.permission.WRITE_EXTERNAL_STORAGE", 
                    //                                                         "android.permission.INTERNET", 
                    //                                                         "android.permission.ACCESS_NETWORK_STATE", 
                    //                                                         "android.permission.ACCESS_WIFI_STATE", 
                    //                                                         "android.permission.READ_PHONE_STATE", 
                    //                                                         "android.permission.GET_TASKS", 
                    //                                                         "android.permission.VIBRATE",
                    //                                                         packageName + ".permission.MIPUSH_RECEIVE"};
                    // AddPermissionToManifest(manifestFilePath, addPermissions);
                    // //for mipush end


















                }

                bool enableOpenInstall = true;
                if(enableOpenInstall)
                {
                    //for openinstall begin
                    if(false)
                    {
                                        string openinstallMainActivityIntentFilter = @"<intent-filter >
                                    <action android:name=""android.intent.action.VIEW""/>
                                    <category android:name=""android.intent.category.DEFAULT""/>
                                    <category android:name=""android.intent.category.BROWSABLE""/>
                                    <data android:scheme=""""/>
                                </intent-filter>
                    ";
                                        AddBefore(manifestFilePath, @"<meta-data android:name=""unityplayer.UnityActivity"" android:value=""true"" />", openinstallMainActivityIntentFilter);
                    }

                    string openinstallApplicationMeta = @"<meta-data android:name=""com.openinstall.APP_KEY"" android:value=""""/>
                    ";
                    AddBefore(manifestFilePath, @"</application>", openinstallApplicationMeta);
                    //for openinstall end
                }



                //begin fix android bug https://feedback.unity3d.com/suggestions/fix-android-8-game-breaking-permission-bug-in-unity-4-dot-7
//                AddBefore(manifestFilePath, @"<meta-data android:name=""unityplayer.UnityActivity"" android:value=""true"" />", @"<meta-data android:name=""unityplayer.SkipPermissionsDialog"" android:value=""true"" />" + "\n");
                //end fix android bug
            }

            ExportProjectSetting(targetGroup, dir);

            if (targetGroup == BuildTargetGroup.Android)
            {
                string codeDir = System.IO.Path.GetFullPath(dir + "/src/main/java");
                string[] mainActivityCodePaths = System.IO.Directory.GetFiles(codeDir, "MainActivity.java", System.IO.SearchOption.AllDirectories);
                if (mainActivityCodePaths.Length > 0)
                {
                    string packageName = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android);

                    string mainActivityCodePath = mainActivityCodePaths[0];
                    string mainActivityContent = CommonUtil.fileToString(mainActivityCodePath);
                    mainActivityContent = mainActivityContent.Replace("${app_packagename}", packageName);
                    CommonUtil.stringToFile(mainActivityCodePath, mainActivityContent);

                    string newActivityPath = mainActivityCodePath.Replace(codeDir + "/", "").Replace(".java", "").Replace("/", ".");

                    string oldActivityPath = packageName + ".UnityPlayerActivity";


                    string manifestPath = dir + "/src/main/AndroidManifest.xml";
                    string manifestStr = CommonUtil.fileToString(manifestPath);

                    manifestStr = manifestStr.Replace(oldActivityPath, newActivityPath);
                    CommonUtil.stringToFile(manifestPath, manifestStr);

                    AppInfo appInfo = Login.GetAppInfo();
                    string[] stringResPaths = CommonUtil.GetFiles(dir + "/src/main/res", "strings.xml", System.IO.SearchOption.AllDirectories);
                    foreach(var resPath in stringResPaths)
                    {
                        string resStr = CommonUtil.fileToString(resPath);
                        resStr = resStr.Replace("${app_name}", appInfo.app_name);
                        CommonUtil.stringToFile(resPath, resStr);
                    }
                }
            }

            Debug.Log("build output dir: " + dir);
        }
        else
        {
            string log = "";
            for(int i = errorMsg.steps.Length - 1; i >= 0; i--)
            {
                BuildStep step = errorMsg.steps[i];
                log += step.name + ":" + step.messages + "\n";
            }

            throw new System.Exception("build error msg: " + log + "\n");
        }
    }

    public static void ExportProjectSetting(BuildTargetGroup target, string dir)
    {
        string projectBuildSettingPath = "project_build_setting";
        if(!CommonUtil.Exists(projectBuildSettingPath))
        {
            projectBuildSettingPath = "Assets/zframework/" + projectBuildSettingPath;
        }
        
        if (target == BuildTargetGroup.Android)
        {
            string srcDir = projectBuildSettingPath + "/android/src/main";
            string destDir = dir + "/src/main";

            string[] filePaths = System.IO.Directory.GetFiles(srcDir, "*", System.IO.SearchOption.AllDirectories);
            for (int i = 0; i < filePaths.Length; i++)
            {
                string filePath = filePaths[i];
                if(filePath.EndsWith(".meta"))
                {
                    continue;
                }

				string destFilePath = filePath.Replace(srcDir, destDir);
                CommonUtil.CreateDir(System.IO.Path.GetDirectoryName(destFilePath));
                CommonUtil.Copy(filePath, destFilePath);
            }
        }
    }

    public static void AddPermissionToManifest(string manifestPath, HashSet<string> addPermissions)
    {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@".*<uses-permission android:name=""(.*)"" />.*");
        string str = CommonUtil.fileToString(manifestPath);
        System.IO.StringReader reader = new System.IO.StringReader(str);
        while (true)
        {
            string line = reader.ReadLine();
            if (line == null)
            {
                break;
            }

            System.Text.RegularExpressions.Match match = regex.Match(line);
            if (match.Success)
            {
                string permission = match.Groups[1].Value;
                addPermissions.Remove(permission);
            }
        }

        string addString = "";
        foreach (string permission in addPermissions)
        {
            addString += @"  <uses-permission android:name=""" + permission + @""" />  <!-- add by AddPermissionToManifest -->" + "\n";
        }

        int index = str.IndexOf(@"</manifest>");
        str = str.Insert(index, addString);

        CommonUtil.stringToFile(manifestPath, str);
    }

    public static void AddBefore(string manifestPath, string findStr, string insertStr)
    {
        string str = CommonUtil.fileToString(manifestPath);
        int index = str.IndexOf(findStr);
        str = str.Insert(index, insertStr);
        CommonUtil.stringToFile(manifestPath, str);
    }

    public static void AddAfter(string manifestPath, string findStr, string insertStr)
    {
        string str = CommonUtil.fileToString(manifestPath);
        int index = str.IndexOf(findStr);
        str = str.Insert(index + findStr.Length, insertStr);
        CommonUtil.stringToFile(manifestPath, str);
    }

    public static void Replace(string manifestPath, string findStr, string insertStr)
    {
        string str = CommonUtil.fileToString(manifestPath);
        str = str.Replace(findStr, insertStr);
        CommonUtil.stringToFile(manifestPath, str);
    }

    public static string[] GetScenePaths()
    {
        List<string> arrScenes = new List<string>();

        for (int i = 0; i < EditorBuildSettings.scenes.Length; i++)
        {
            EditorBuildSettingsScene scene = EditorBuildSettings.scenes[i];
            if (scene.enabled && System.IO.File.Exists(scene.path))
            {
                arrScenes.Add(scene.path);
            }
        }

        string[] scenes = arrScenes.ToArray();
        return scenes;
    }

    public static string BuildTargetGroupToAppInfoKey(BuildTargetGroup g)
    {
        switch(g)
        {
            case BuildTargetGroup.iOS:
                return BuildTarget.iOS.ToString().ToLower();
            default:
                return g.ToString().ToLower();
        }
    }

    [PostProcessBuildAttribute(1)]
    public static void OnPostprocessBuild(BuildTarget buildTarget, string outputProjectPath)  
    {  
        #if UNITY_IOS
        if (buildTarget == BuildTarget.iOS)
        {
            string projPath = PBXProject.GetPBXProjectPath(outputProjectPath);  
            PBXProject proj = new PBXProject();  

            System.IO.File.Copy(projPath, projPath + ".backup");

            proj.ReadFromString(System.IO.File.ReadAllText(projPath));  

            // 获取当前项目名字  
            string target = proj.TargetGuidByName(PBXProject.GetUnityTargetName());  

            // 对所有的编译配置设置选项  
            proj.SetBuildProperty(target, "ENABLE_BITCODE", "NO");  

//            // 添加依赖库  
//            proj.AddFrameworkToProject (target, "Security.framework", false);  
//            proj.AddFrameworkToProject (target, "JavaScriptCore.framework", false);  
//            proj.AddFrameworkToProject (target, "libc++.1.tbd", false);  
//            proj.AddFrameworkToProject (target, "libz.1.tbd", false);  

            proj.WriteToFile(projPath);
          




            //for mipush begin
            ProjectCapabilityManager mgr = new ProjectCapabilityManager(projPath, "base.entitlements", PBXProject.GetUnityTargetName());
            mgr.AddPushNotifications(VersionEx.compile_type != CompileType.release && VersionEx.compile_type != CompileType.beta);
            mgr.WriteToFile();

            string infoPlistPath = System.IO.Path.Combine(outputProjectPath, "Info.plist");
            System.IO.File.Copy(infoPlistPath, infoPlistPath + ".backup");
            PlistDocument plistDoc = new PlistDocument();
            plistDoc.ReadFromFile(infoPlistPath);



//            plistDoc.root.values.Remove("UIApplicationExitsOnSuspend");
            plistDoc.root.SetString("NSLocationWhenInUseUsageDescription", "Location");
//            plistDoc.root.SetString("NSMicrophoneUsageDescription", "Microphone");
            //for file shared
//            plistDoc.root.SetBoolean("UIFileSharingEnabled", true);


            bool enbleOpeninstall = true;
            if(enbleOpeninstall)
            {
                plistDoc.root.SetString("com.openinstall.APP_KEY", "aaaaa");
            }

            plistDoc.WriteToFile(infoPlistPath);





            //for multi lang begin
            string iosSettingPath = System.IO.Path.Combine("project_build_setting", "ios");
            NativeLocale.AddLocalizedStringsIOS(outputProjectPath, iosSettingPath);
            //for multi lang end



//            //for iphone home indicator begin
//            string viewControllerForIOSFilePath = System.IO.Path.Combine(outputProjectPath, "Classes/UI/UnityViewControllerBaseiOS.mm");
//            string str = CommonUtil.fileToString(viewControllerForIOSFilePath);
//            string srcStr = "@implementation UnityViewControllerBase";
//            if (str.Contains(srcStr))
//            {
//                Debug.Log("contain: " + srcStr);
//            }
//
//            str = str.Replace(srcStr, srcStr + @"
//-(UIRectEdge)preferredScreenEdgesDeferringSystemGestures
//{
//    return UIRectEdgeAll;
//}
//");
//            CommonUtil.stringToFile(viewControllerForIOSFilePath, str);
//            //for iphone home indicator end
        }
        #endif
    }
//    #endif
}
